#include "Timeline.h"
#include "File.h"
#include "ObjUsefulFunctions.h"
#include <string>
#include "StringUtil.h"
#include "Factory.h"
#include "ReportError.h"
#include "TimeLineKeyFactory.h"
#include "Timer.h"
#include "FloatUtils.h"

Timeline::Timeline()
{
	m_Time = 0;
	m_it = TheTLKMap.begin();
}

bool Timeline::Load(const std::string& FileName)
{
	File TempFile;

	if(!TempFile.OpenRead(FileName))
	{
		return false;
	}


	std::string TempStr;
	while(TempFile.GetString(&TempStr))
	{

		static float LastTime = 0;
		float Time = 0;
		Strings Str = Split(TempStr, ' ');

		if(Str.size() == 2)
		{
			if(Str[0] == "+")
				Time = (LastTime += ToFloat(Str[1]));
		}
		else if(Str.size() == 1)
		{
			Time = ToFloat(Str[0]);
			LastTime = Time;
		}


		if(!TempFile.GetString(&TempStr))
		{
			//get line from file class
			ReportError("Expected A TimelineKey!!!");
			return false;
		}

		TimelineKey* tlk =TheTLKFactory::Instance()->Create(TempStr);

		if(tlk == nullptr)
		{
			ReportError("No Such TimeLineKey");
		}


		tlk->Load(&TempFile);
		TheTLKMap.insert(std::make_pair(Time, tlk));


	}
	return true;
}

void Timeline::Update()
{
	m_Time += TheTimer::Instance()->GetDeltaTime();

	for(std::multimap<float,TimelineKey*>::iterator it = TheTLKMap.begin(); it != TheTLKMap.end(); ++it)
	{
		if(CompFloat(m_Time, it->first, 0.1f))
		{
			it->second->Exec();
		}
	}

	//check i'm not at the end of the map


	//while (true)
	//{
	//	if(m_it->first <= m_Time)
	//	{
	//		m_it->second->Exec();
	//	}
	//	else { break; }
	//	++m_it;
	//}

	std::cout << m_Time << "\n";
}